<template>
  <div class="system-user-container">
    <el-row :gutter="10" style="width: 100%;">
      <el-col :span="4">
        <el-card shadow="hover">
          <el-aside>
            <el-scrollbar>
              <el-input prefix-icon="search" v-model="filterText" placeholder="请输入部门名称" clearable size="default"
                style="width: 80%;" />
              <el-tree ref="treeRef" class="filter-tree" :data="deptData" default-expand-all
                :filter-node-method="deptFilterNode" @node-click="handleNodeClick" />
            </el-scrollbar>
          </el-aside>
        </el-card>
      </el-col>
      <el-col :span="20">
        <el-card shadow="hover">
          <div class="system-user-search mb15">
            <el-form :model="tableData.param" ref="queryRef" :inline="true" label-width="68px">
              <el-form-item label="手机号码" prop="phone">
                <el-input v-model="tableData.param.phone" maxlength="11" placeholder="请输入手机号码" clearable size="default"
                  style="width: 240px" @keyup.enter.native="userList" />
              </el-form-item>
              <el-form-item label="状态" prop="status" style="width: 200px;">
                <el-select v-model="tableData.param.status" placeholder="用户状态" clearable size="default"
                  style="width: 240px">
                  <el-option label="正常" :value="1" />
                  <el-option label="停用" :value="0" />
                </el-select>
              </el-form-item>
              <el-form-item label="创建时间" prop="dateRange">
                <el-date-picker v-model="tableData.param.dateRange" type="datetimerange" size="default"
                  style="width: 300px" range-separator="-" start-placeholder="开始日期"
                  end-placeholder="结束日期"></el-date-picker>
              </el-form-item>
              <el-form-item>
                <el-button size="default" type="primary" class="ml10" @click="userList">
                  <el-icon>
                    <Search />
                  </el-icon>
                  查询
                </el-button>
                <el-button size="default" @click="resetQuery(queryRef)">
                  <el-icon>
                    <Refresh />
                  </el-icon>
                  重置
                </el-button>
                <el-button v-if="permissionStore.isPermissionsBtn('001001001')" size="default" type="success"
                  class="ml10" @click="onOpenAddUser">
                  <el-icon>
                    <FolderAdd />
                  </el-icon>
                  新增用户
                </el-button>
              </el-form-item>
            </el-form>
          </div>
          <el-table :data="tableData.data" style="width: 100%">
            <!-- <el-table-column type="selection" width="55" align="center" /> -->
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column prop="userName" label="账户名称" show-overflow-tooltip></el-table-column>
            <el-table-column prop="nickName" label="用户昵称" show-overflow-tooltip></el-table-column>
            <!-- <el-table-column prop="deptId" label="部门ID" show-overflow-tooltip></el-table-column> -->
            <el-table-column prop="deptName" label="部门名称" show-overflow-tooltip></el-table-column>
            <!-- <el-table-column prop="email" label="用户邮箱" show-overflow-tooltip></el-table-column> -->
            <el-table-column prop="email" label="关联角色" show-overflow-tooltip min-width="100">
              <template #default="{ row }">
                <el-tag v-for="tag in row.roleNames" :key="tag" class="tag-item ml5" type="primary">
                  {{ tag }}
                </el-tag>
              </template>
            </el-table-column>

            <el-table-column prop="phone" label="手机号码" show-overflow-tooltip></el-table-column>
            <el-table-column label="性别" align="center" :show-overflow-tooltip="true">
              <template #default="scope">
                {{ scope.row.sex == 1 ? '男' : scope.row.sex == 2 ? '女' : '未知' }}
              </template>
            </el-table-column>
            <!-- <el-table-column label="头像" align="center">
              <template #default="scope">
                <el-avatar v-if="scope.row.active" :size="50" :src="scope.row.active" />
                <div v-else>未设置</div>
              </template>
            </el-table-column> -->
            <!-- <el-table-column label="角色" align="center" prop="roleInfo" :show-overflow-tooltip="true">
              <template #default="scope">
                <span v-for="(item, index) of scope.row.roleInfo" :key="'role-' + index"> {{ item.name + ' ' }} </span>
              </template>
            </el-table-column> -->
            <el-table-column prop="createTimeTxt" label="创建时间" show-overflow-tooltip align="center"
              min-width="150"></el-table-column>
            <!-- <el-table-column prop="createBy" label="创建人员" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column prop="createTimeTxt" label="创建时间" show-overflow-tooltip></el-table-column>
            <el-table-column prop="updateBy" label="更新人员" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column prop="updateTimeTxt" label="更新时间" show-overflow-tooltip></el-table-column>
            <el-table-column prop="remark" label="备注" show-overflow-tooltip></el-table-column> -->
            <el-table-column prop="status" label="用户状态" align="center" show-overflow-tooltip>
              <template #default="scope">
                <el-tag type="success" v-if="scope.row.status === 1">正常</el-tag>
                <el-tag type="info" v-else>停用</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" min-width="250" v-if="permissionStore.isPermissionsBtn(['001001002','001001003','001001004'])">
              <template #default="scope">
                <el-button size="small" v-if="permissionStore.isPermissionsBtn('001001002')" text type="warning"
                  @click="onOpenEditUser(scope.row)">修改</el-button>
                <el-button size="small" v-if="permissionStore.isPermissionsBtn('001001003')" text type="danger"
                  @click="onRowDel(scope.row)">删除</el-button>
                <el-button size="small" text type="success" @click="onOpenDetailsUser(scope.row)">详情</el-button>
                <el-button size="small" v-if="permissionStore.isPermissionsBtn('001001004')" text type="primary"
                  @click="handleResetPwd(scope.row)">重置</el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-show="tableData.total > 0" :total="tableData.total" v-model:page="tableData.param.pageNumber"
            v-model:limit="tableData.param.pageLength" @pagination="userList" />
        </el-card>
      </el-col>
    </el-row>
    <EditUser ref="editUserRef" :dept-data="deptData" :role-data="roleData" :acType="acType" @getUserList="userList" />
    <DetailsUser ref="detailsUserRef" :dept-data="deptData" :role-data="roleData" />
  </div>
</template>

<script lang="ts">
import { toRefs, reactive, onMounted, ref, defineComponent, watch, getCurrentInstance } from 'vue';
import { ElMessageBox, ElMessage, ElTree, FormInstance } from 'element-plus';
import EditUser from './component/editUser.vue';
import DetailsUser from './component/detailsUser.vue';
import { getUserListApi, delUserApi, resetUserPasswordApi } from '@/api/auth/user';
import { treeDeptApi } from '@/api/auth/dept'
import { getRoleListApi } from '@/api/auth/role'
import { formatDateTime, dateToTimestamp } from '@/utils'
import { usePermissionStore } from '@/store/modules/permission'
interface TableDataState {
  deptData: any[];
  roleData: any[];
  acType: String,
  tableData: {
    data: any[];
    total: number;
    loading: boolean;
    param: {
      pageNumber: number;
      pageLength: number;
      userId: String,
      deptId: string;  //部门id
      phone: String,
      status: string;
      beginTime: String, //开始时间
      endTime: String  //结束时间
      dateRange: any[]
    };
  };
}

export default defineComponent({
  name: 'systemUser',
  components: { EditUser, DetailsUser },
  setup() {
    const { proxy } = <any>getCurrentInstance();
    const editUserRef = ref();
    const detailsUserRef = ref()
    const queryRef = ref();
    const filterText = ref('');
    const treeRef = ref<InstanceType<typeof ElTree>>();
    const state = reactive<TableDataState>({
      deptData: [],
      roleData: [],
      acType: '',
      tableData: {
        data: [],
        total: 0,
        loading: false,
        param: {
          pageNumber: 1,
          pageLength: 10,
          deptId: '',
          status: '',
          userId: '',
          phone: '',
          beginTime: '',
          endTime: '',
          dateRange: []
        },
      },
    });

    const permissionStore = usePermissionStore()

    // 初始化表格数据
    const initTableData = () => {
      treeDeptApi().then((res: any) => {
        state.deptData = res.data
      })
      roleList()  //获取角色列表
      userList();
    };
    const userList = () => {
      const { dateRange, ...newParam } = state.tableData.param
      let beginTime = dateToTimestamp(dateRange[0])
      let endTime = dateToTimestamp(dateRange[1])
      let obj = {
        ...newParam,
        beginTime: beginTime ? beginTime : '',
        endTime: endTime ? endTime : '',
      }
      getUserListApi(obj).then((res: any) => {
        state.tableData.data = res.data.list.map(item => {
          let obj = {
            updateTimeTxt: formatDateTime(item.updateTime),
            createTimeTxt: formatDateTime(item.createTime),
            ...item
          }
          return obj
        })
        state.tableData.total = res.data.total;
      });
    };
    // 获取角色列表
    const roleList = () => {
      getRoleListApi({ padding: 2 }).then((res: any) => {
        state.roleData = res.data.list
      })
    }

    // 打开新增用户弹窗
    const onOpenAddUser = () => {
      state.acType = 'add'
      editUserRef.value.openDialog();
    };
    // 打开修改用户弹窗
    const onOpenEditUser = (row: any) => {
      state.acType = 'edit'
      editUserRef.value.openDialog(row);
    };
    // 打开详情用户弹窗
    const onOpenDetailsUser = (row: any) => {
      detailsUserRef.value.openDialog(row.userId);
    };
    // 删除用户
    const onRowDel = (row: any) => {
      let msg = `此操作将永久删除用户：“${row.userName}”，是否继续?`
      ElMessageBox.confirm(msg, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          delUserApi({ id: row.userId }).then(() => {
            ElMessage.success('删除成功');
            userList();
          })
        })
        .catch(() => { });
    };
    // 页面加载时
    onMounted(() => {
      initTableData();
    });
    watch(filterText, (val) => {
      treeRef.value!.filter(val)
      console.log(treeRef.value!.filter(val));

    });
    const deptFilterNode = (value: string, data: any) => {
      if (!value) return true;
      return data.label.includes(value)
    };
    // 节点单击事件
    const handleNodeClick = (data: any) => {
      console.log(data);

      state.tableData.param.deptId = data.id;
      userList();
    };
    /** 重置密码按钮操作 */
    const handleResetPwd = (row: any) => {
      ElMessageBox.prompt('请输入"' + row.userName + '"的新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      }).then(({ value }) => {
        if (!value || value == '') {
          ElMessage.error('密码不能为空');
          return
        }
        resetUserPasswordApi({ userName: row.userName, password: value }).then(() => {
          ElMessage.success("修改成功，新密码是：" + value);
        });
      }).catch(() => { });
    };
    /** 重置按钮操作 */
    const resetQuery = (formEl: FormInstance | undefined) => {
      if (!formEl) return
      formEl.resetFields()
      state.tableData.param.deptId = null
      userList()
    };
    return {
      queryRef,
      editUserRef,
      detailsUserRef,
      onOpenAddUser,
      onOpenEditUser,
      onOpenDetailsUser,
      onRowDel,
      deptFilterNode,
      filterText,
      treeRef,
      userList,
      handleNodeClick,
      handleResetPwd,
      permissionStore,
      resetQuery,
      ...toRefs(state),
    };
  },
});
</script>
